//
//  NSDate+YLAddDateInfo.m
//  yuLink
//
//  Created by aiwoba on 2021/3/15.
//

#import "NSDate+YLAddDateInfo.h"

@implementation NSDate (YLAddDateInfo)
/**
 计算时间差 以 小时 为单位
 
 @param startDate  开始时间
 @param endTimeDate 结束时间
 @return 时间差
 */
+(NSMutableString * )dateGetTimeDifferenceStartDate:(NSDate *)startDate endTimeDate:(NSDate *)endTimeDate{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSCalendarUnit type = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    NSDateComponents *compas = [calendar components:type fromDate:startDate toDate:endTimeDate options:0];

    NSMutableString *mstring = [NSMutableString string];
    if (compas.year>0) {
        [mstring appendString:[NSString stringWithFormat:@"%ld年",compas.year]];
    }
    if (compas.month > 0) {
        [mstring appendString:[NSString stringWithFormat:@"%ld月",compas.month]];
    }
    if (compas.day > 0) {
        [mstring appendString:[NSString stringWithFormat:@"%ld天",compas.day]];
    }
    if (compas.hour > 0) {
        [mstring appendString:[NSString stringWithFormat:@"%ld小时",compas.hour]];
    }
    if (compas.minute > 0) {
        [mstring appendString:[NSString stringWithFormat:@"%ld分",compas.minute]];
    }
    if (compas.second > 0) {
        [mstring appendString:[NSString stringWithFormat:@"%ld秒",compas.second]];
    }
    return  mstring;
}

/**
 计算时间差  总分钟
 @param startDate  开始时间
 @param endTimeDate 结束时间
 @return 时间差
 */
+(long long )dateTotalMinuteTimeDifferenceStartDate:(NSDate *)startDate endTimeDate:(NSDate *)endTimeDate{
    long long totalMinutime = 0;
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSCalendarUnit type = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    NSDateComponents *compas = [calendar components:type fromDate:startDate toDate:endTimeDate options:0];

    if (compas.day > 0) {
        totalMinutime += compas.day * 24 * 60 ;
    }
    if (compas.hour > 0) {
        totalMinutime += compas.hour * 60;
    }
    if (compas.minute > 0) {
        totalMinutime += compas.minute;
    }

    return  totalMinutime;
}

/**
 计算时间差  总秒数
 @param startDate  开始时间
 @param endTimeDate 结束时间
 @return 时间差
 */
+(long long )dateTotalSecondTimeDifferenceStartDate:(NSDate *)startDate endTimeDate:(NSDate *)endTimeDate{
    long long totalMinutime = 0;
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSCalendarUnit type = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    NSDateComponents *compas = [calendar components:type fromDate:startDate toDate:endTimeDate options:0];

    if (compas.day > 0) {
        totalMinutime += compas.day * 24 * 60 ;
    }
    if (compas.hour > 0) {
        totalMinutime += compas.hour * 60;
    }
    if (compas.minute > 0) {
        totalMinutime += compas.minute;
    }
    long long totalSecond = totalMinutime * 60;
    if (compas.second > 0) {
        totalSecond = totalSecond + compas.second;
    }
    return  totalSecond;
}
/**
 格式化时间类型 为  服务器传的年月日时分秒

 @param timestampStr 服务器给的
 @param format 想要格式化的类型
 @return 格式化好的时间字符串
 */
+(NSString *)dateFormatterTimeStr:(NSString *)timestampStr andFormatter:(NSString *)format{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:format]; // （@"YYYY-MM-dd hh:mm:ss"）----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *confromTimesp = [dateFormatter dateFromString:timestampStr];
    NSString *confromTimespStr = [formatter stringFromDate:confromTimesp];
    return confromTimespStr;
    
}

+(NSDate *)dateTimesDateWithTime:(long long int)timestamp andFormatter:(NSString *)format{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:format]; // （@"YYYY-MM-dd hh:mm:ss"）----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];
    NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:timestamp/1000.0];
    return confromTimesp;
    
}
///timestampStr 服务器给的字段
+(NSDate *)dateTimesDateWithTimeString:(NSString *)timestampStr andFormatter:(NSString *)format{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:format]; // （@"YYYY-MM-dd hh:mm:ss"）----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *confromTimesp = [dateFormatter dateFromString:timestampStr];
    return confromTimesp;
    
}

///获取当前时间戳有两种方法(以秒为单位)
+(NSString *)dateGetNowTimeTimestampSecond{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];
    return timeSp;
    
}

///获取当前时间戳  （以毫秒为单位）
+(NSString *)dateGetNowTimeTimestampStrMillisecond{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss SSS"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    //设置时区,这个对于时间的处理有时很重要
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]*1000];
    return timeSp;
}
///获取当前时间戳  （以毫秒为单位）
+(NSDate *)dateGetNowTimeTimestampStrMillisecondDate{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss SSS"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    //设置时区,这个对于时间的处理有时很重要
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    return datenow;
}

-(BOOL)inFestival{
    NSTimeInterval timeInterval_day = 60 * 60 * 24;
      
    NSDate *nextDay_date = [NSDate dateWithTimeInterval:timeInterval_day sinceDate:self];
      
    NSCalendar *localeCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierChinese];
      
    unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay;
      
    NSDateComponents *localeComp = [localeCalendar components:unitFlags fromDate:nextDay_date];
      // 12
    if ( (1 == localeComp.month && localeComp.day < 16)  || (localeComp.month == 12 && localeComp.day >= 24)) {
          
        return YES;
    }
    return NO;
}

- (NSString *)lunarHoliDayDate{
    
    NSTimeInterval timeInterval_day = 60 * 60 * 24;
      
    NSDate *nextDay_date = [NSDate dateWithTimeInterval:timeInterval_day sinceDate:self];
      
    NSCalendar *localeCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierChinese];
      
    unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay;
      
    NSDateComponents *localeComp = [localeCalendar components:unitFlags fromDate:nextDay_date];
      
    if ( 1 == localeComp.month && 1 == localeComp.day ) {
          
        return @"除夕";
    }
    NSDictionary *chineseHoliDay = [NSDictionary dictionaryWithObjectsAndKeys:
                                      
                                    @"春节", @"1-1",
                                      
                                    @"元宵", @"1-15",
                                      
                                    @"端午", @"5-5",
                                      
                                    @"七夕", @"7-7",
                                      
                                    @"中元", @"7-15",
                                      
                                    @"中秋", @"8-15",
                                      
                                    @"重阳", @"9-9",
                                      
                                    @"腊八", @"12-8",
                                      
                                    @"小年", @"12-24",
                                      
                                    nil];
      
    localeComp = [localeCalendar components:unitFlags fromDate:self];
      
    NSString *key_str = [NSString stringWithFormat:@"%ld-%ld",(long)localeComp.month,(long)localeComp.day];
      
    return [chineseHoliDay objectForKey:key_str];
}

///获取当前时间的字符串 @"YYYY-MM-dd HH:mm:ss "
+(NSString *)dateGetCurrentTimeWithFormatterSting:(NSString *)formatterString{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
     [formatter setDateFormat:formatterString]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
      NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];
    NSDate *datenow = [NSDate date];
 
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    currentTimeString = [NSString stringWithFormat:@"%@",currentTimeString];
    return currentTimeString;
}
///获取当前时间的字符串 @"YYYY-MM-dd HH:mm:ss "
+(NSString *)dateGetCurrentTimeWithFormatterStingAddRandomNum:(NSString *)formatterString{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
     [formatter setDateFormat:formatterString]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
      NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];
    NSDate *datenow = [NSDate date];
 
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    int n = (arc4random() % 10000);
    currentTimeString = [NSString stringWithFormat:@"%@%d",currentTimeString,n];
    return currentTimeString;
}


//+(NSDate * )dateAfterLocalDateForlocalDate:(NSDate *)locaDate Year:(NSInteger )year Month:(NSInteger )month day:(NSInteger)day hour:(NSInteger)hour minute:(NSInteger)minute second:(NSInteger)second{
//    NSCalendar *calendar = [NSCalendar currentCalendar];
//
//    NSDateComponents *componnents = [[NSDateComponents alloc] init];
//    [componnents setYear:year];
//    [componnents setMonth:month];
//    [componnents setDay:day];
//    [componnents setHour:hour];
//    [componnents setMinute:minute];
//    [componnents setSecond:second];
//    NSDate *timeDate = [calendar dateByAddingComponents:componnents toDate:locaDate options:0];
//    return timeDate;
//}

- (NSInteger)year {
    return [[[NSCalendar currentCalendar] components:NSCalendarUnitYear fromDate:self] year];
}

- (NSInteger)month {
    return [[[NSCalendar currentCalendar] components:NSCalendarUnitMonth fromDate:self] month];
}

- (NSInteger)day {
    return [[[NSCalendar currentCalendar] components:NSCalendarUnitDay fromDate:self] day];
}

- (NSInteger)hour {
    return [[[NSCalendar currentCalendar] components:NSCalendarUnitHour fromDate:self] hour];
}

- (NSInteger)minute {
    return [[[NSCalendar currentCalendar] components:NSCalendarUnitMinute fromDate:self] minute];
}

- (NSInteger)second {
    return [[[NSCalendar currentCalendar] components:NSCalendarUnitSecond fromDate:self] second];
}

- (NSInteger)nanosecond {
    return [[[NSCalendar currentCalendar] components:NSCalendarUnitSecond fromDate:self] nanosecond];
}

- (NSInteger)weekday {
    return [[[NSCalendar currentCalendar] components:NSCalendarUnitWeekday fromDate:self] weekday];
}

- (NSInteger)weekdayOrdinal {
    return [[[NSCalendar currentCalendar] components:NSCalendarUnitWeekdayOrdinal fromDate:self] weekdayOrdinal];
}

- (NSInteger)weekOfMonth {
    return [[[NSCalendar currentCalendar] components:NSCalendarUnitWeekOfMonth fromDate:self] weekOfMonth];
}

- (NSInteger)weekOfYear {
    return [[[NSCalendar currentCalendar] components:NSCalendarUnitWeekOfYear fromDate:self] weekOfYear];
}

- (NSInteger)yearForWeekOfYear {
    return [[[NSCalendar currentCalendar] components:NSCalendarUnitYearForWeekOfYear fromDate:self] yearForWeekOfYear];
}

- (NSInteger)quarter {
    return [[[NSCalendar currentCalendar] components:NSCalendarUnitQuarter fromDate:self] quarter];
}

- (BOOL)isLeapMonth {
    return [[[NSCalendar currentCalendar] components:NSCalendarUnitQuarter fromDate:self] isLeapMonth];
}

- (BOOL)isLeapYear {
    NSUInteger year = self.year;
    return ((year % 400 == 0) || ((year % 100 != 0) && (year % 4 == 0)));
}

- (BOOL)isToday {
    if (fabs(self.timeIntervalSinceNow) >= 60 * 60 * 24) return NO;
    return [NSDate new].day == self.day;
}

- (BOOL)isYesterday {
    NSDate *added = [self dateByAddingDays:1];
    return [added isToday];
}

- (NSDate *)dateByAddingYears:(NSInteger)years {
    NSCalendar *calendar =  [NSCalendar currentCalendar];
    NSDateComponents *components = [[NSDateComponents alloc] init];
    [components setYear:years];
    return [calendar dateByAddingComponents:components toDate:self options:0];
}

- (NSDate *)dateByAddingMonths:(NSInteger)months {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [[NSDateComponents alloc] init];
    [components setMonth:months];
    return [calendar dateByAddingComponents:components toDate:self options:0];
}

- (NSDate *)dateByAddingWeeks:(NSInteger)weeks {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [[NSDateComponents alloc] init];
    [components setWeekOfYear:weeks];
    return [calendar dateByAddingComponents:components toDate:self options:0];
}

- (NSDate *)dateByAddingDays:(NSInteger)days {
//    NSTimeInterval aTimeInterval = [self timeIntervalSinceReferenceDate] + 86400 * days;
//    NSDate *newDate = [NSDate dateWithTimeIntervalSinceReferenceDate:aTimeInterval];
//    return newDate;
    return [self dateByAddingTimeInterval:days * 60 * 60 * 24];
}

- (NSDate *)dateByAddingHours:(NSInteger)hours {
    NSTimeInterval aTimeInterval = [self timeIntervalSinceReferenceDate] + 3600 * hours;
    NSDate *newDate = [NSDate dateWithTimeIntervalSinceReferenceDate:aTimeInterval];
    return newDate;
}

- (NSDate *)dateByAddingMinutes:(NSInteger)minutes {
    NSTimeInterval aTimeInterval = [self timeIntervalSinceReferenceDate] + 60 * minutes;
    NSDate *newDate = [NSDate dateWithTimeIntervalSinceReferenceDate:aTimeInterval];
    return newDate;
}

- (NSDate *)dateByAddingSeconds:(NSInteger)seconds {
    NSTimeInterval aTimeInterval = [self timeIntervalSinceReferenceDate] + seconds;
    NSDate *newDate = [NSDate dateWithTimeIntervalSinceReferenceDate:aTimeInterval];
    return newDate;
}

/**
 计算时间差  天/时/分
 @param startDate  开始时间
 @param endTimeDate 结束时间
 @return 时间差
 */
+(NSString *)dateTotalTimeDifferenceStartDate:(NSDate *)startDate endTimeDate:(NSDate *)endTimeDate{
    //  时区相差8个小时 加上这个时区即是北京时间
    NSTimeInterval timeinterval = [endTimeDate timeIntervalSinceDate:startDate];
    NSInteger days = timeinterval / 60 / 60 / 24;
    NSInteger hours = (timeinterval - days * 60 * 60 * 24) / 3600;
    NSInteger mins = (timeinterval - days * 60 * 60 * 24 - hours * 3600) / 60;
    if (days > 0) {
        NSString *result = [NSString stringWithFormat:@"%li天%li时%li分",days,hours,mins];
        return result;
    } else {
        NSString *result = [NSString stringWithFormat:@"%li时%li分",hours,mins];
        return result;
    }
//    NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
//    NSInteger delta = [timeZone secondsFromGMT];
//    startDate = [startDate dateByAddingTimeInterval:delta];
//    endTimeDate = [endTimeDate dateByAddingTimeInterval:delta];
//    NSCalendar *calendar = [NSCalendar currentCalendar];
//    NSCalendarUnit type = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
//    NSDateComponents *compas = [calendar components:type fromDate:startDate toDate:endTimeDate options:0];
//
//    NSString *time = @"";
//
//    if (compas.day > 0) {
//        time = [NSString stringWithFormat:@"%li天%li时%li分",compas.day,compas.hour,compas.minute];
//    }else{
//        if (compas.hour > 0) {
//            time = [NSString stringWithFormat:@"%li时%li分",compas.hour,compas.minute];
//        }else{
//            if (compas.minute > 0) {
//                time = [NSString stringWithFormat:@"%li分",compas.minute];
//            }
//        }
//    }
//    return  time;
}
/**
 计算时间差
 @param startDate  开始时间
 @param endTimeDate 结束时间
 @return 时间差
 */
+(NSDateComponents *)dateComponentsDifferenceStartDate:(NSDate *)startDate endTimeDate:(NSDate *)endTimeDate{
    //  时区相差8个小时 加上这个时区即是北京时间
    NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
    NSInteger delta = [timeZone secondsFromGMT];
    startDate = [startDate dateByAddingTimeInterval:delta];
    endTimeDate = [endTimeDate dateByAddingTimeInterval:delta];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSCalendarUnit type = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    NSDateComponents *compas = [calendar components:type fromDate:startDate toDate:endTimeDate options:0];
    return  compas;
}
@end
